from src.plugin import Plugin
from src.item import Item

import requests

class API:

    def __init__(self):
        self.host = 'http://127.0.0.1:5000/api/v1.0/'

        try: requests.get(self.host)
        except: 
            print("Error: Server not responsable")
            exit(1)

    def get_plugins(self):
        url = self.host + 'getPlugins'
        resp = requests.get(url)

        plugins = list()
        jsitems = resp.json()
        for jsitem in jsitems:
            plugin = Plugin.from_json(jsitem)
            plugins.append(plugin)

        return plugins

    def get_plugin_items(self, id):
        url = self.host + 'getPluginItems/' + str(id)
        resp = requests.get(url)

        items = list()
        jsitems = resp.json()
        plugin = Plugin.from_json(jsitems)
        for jsitem in jsitems['items']:
            item = Item.from_json(jsitem)
            items.append(item)

        return plugin, items

    def do_plugin_action(self, id, action, uinput):
        url = f"{self.host}doPluginAction/{id}?action={action}"
        if not uinput is None: url += f"&input={uinput}"
        resp = requests.get(url)

        return resp.json()['result']


